package com.topisv.tms.web.work;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.work.WorkBatch;
import com.topisv.tms.entity.work.WorkLog;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.work.WorkBatchService;
import com.topisv.tms.service.work.WorkLogService;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.utils.DateUtils;
import com.topisv.tms.web.base.BaseController;

/**
 * 商发宝工作日志
 * @author ch
 *
 */
@Controller
@RequestMapping(value = "/workMsg")
public class WorkMsgController extends BaseController{

	private static final Logger logger = LoggerFactory.getLogger(WorkMsgController.class);

	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private WorkBatchService workBatchService;
	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private WorkLogService workLogService;
	@Autowired
	private WorkTaskService workTaskService;
	
	/**
	 * 导向作业信息页面
	 * 继承基类的方式
	 * @param 
	 * @return 
	 * @author <a href=mailto:libin@nryuncang.com>libin</a>
	 * @version 1.0.0
	 */
	@RequestMapping(value = "v2_toWorkMsgPage")
	public String toWorkMsgPage(Model model, ServletRequest request) {
		try {
		    
		    fillSelectValue(model,null);
			ShiroUser curUser = getShiroUser();
//			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
//			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			  
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "work/msg/workMsgList";
	}
	
	/**
	 * 分页查询作业信息
	 * 
	 * @param 
	 * @return 
	 * @author <a href=mailto:libin@nryuncang.com>libin</a>
	 * @version 1.0.0
	 */
    @RequestMapping(value = "v2_queryWorkMsg", method = RequestMethod.POST)
    public void queryWorkMsg(@RequestBody JSONParam[] paramJson, HttpServletResponse response) {
        
        PrintWriter out = null;
        JSONObject json = null;
        Page<WorkBatch> page = null;
        try {
            out = response.getWriter();
            json = new JSONObject();
            ShiroUser curUser = getShiroUser();
            Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
            
            int start = Integer.parseInt(paramMap.get("iDisplayStart"));
            int length = Integer.parseInt(paramMap.get("iDisplayLength"));
            int curPage = (start / length) + 1;
            String sEcho = paramMap.get("sEcho");
           
            Map<String, Object> param = getParameter(curUser, paramMap);
            
            page = workBatchService.loadPageWorkBatch(param, curPage, length);
            List<WorkBatch> workBatchList = page.getContent();
            
            json.put("aaData", workBatchList);
            json.put("sEcho", sEcho);
            json.put("iTotalRecords", page.getTotalElements());
            json.put("iTotalDisplayRecords", page.getTotalElements());
            
            out.print(json);
            
        } catch (Exception e) {
            log.error("搜索查询异常", e);
        }
    }
	
	/**
	 * 查询作业信息
	 * 废弃该方法,使用分页的方式 LiBin 20160808
	 * @param model
	 * @param request
	 * @return
	 */
    @Deprecated
	@RequestMapping(value = "v2_queryWorkMsgBak")
	public String queryWorkMsgBak(Model model, ServletRequest request) {
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//入库单查询结果
			List<WorkBatch> batchList=null;
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			
			String taskCode=(String) param.get("taskCode");
			String orderno=(String) param.get("orderno");
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			String customerCode=(String) param.get("customerCode");
			if(StringUtils.isBlank(customerCode)){
				param.put("customerCodes", this.customersService.loadCustomerByAuthority(curUser.jobuuid));
			}else{
				param.put("customerCodes", customerCode);
			}
			String warehouseCode=(String) param.get("warehouseCode");
			
			
			
			//根据任务号查询
			if(StringUtils.isNotBlank(taskCode)){
				batchList=new ArrayList<WorkBatch>();
				WorkTask task=this.workTaskService.loadTaskByCode(taskCode);
				if(task!=null){
					WorkBatch batch=this.workBatchService.loadWorkBatchByCode(task.getBatchCode());
					batchList.add(batch);
					model.addAttribute("batchList", batchList);
				}
			}
			//根据订单号查询
			else if(StringUtils.isNotBlank(orderno)){
				batchList=new ArrayList<WorkBatch>();
				WorkOrder order=this.workOrderService.loadByOrdernoOrCustomerorderno(orderno);
				if(order!=null){
					WorkBatch batch=this.workBatchService.loadWorkBatchByCode(order.getBatchCode());
					batchList.add(batch);
					model.addAttribute("batchList", batchList);
				}
			}
			//综合信息查询
			else{
				
				Date fromDate=null;
				Date toDate=null;
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				
				if(StringUtils.isNotEmpty(fromDateStr)){
					fromDate=sdf.parse(fromDateStr+" 00:00:00");
				}
				if(StringUtils.isNotEmpty(toDateStr)){
					toDate=sdf.parse(toDateStr+" 23:59:59");
				}
				param.put("fromDate", fromDate);
				param.put("toDate", toDate);
				
				
				if(StringUtils.isBlank(warehouseCode)){
					param.put("areagroups", curUser.areagroups);
				}else{
					param.put("areagroups", warehouseCode);
				}
				
				batchList = this.workBatchService.loadWorkBatch(param);
				model.addAttribute("batchList", batchList);
			}
			
			//初始化仓库数据
			if(StringUtils.isNotBlank(customerCode)){
				List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
			}
			
			model.addAttribute("param", Servlets.encodeParameterStringWithPrefix(param, "_"));
			  
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/msg/workMsgList";
	}
	
    /**
     * 组合查询参数
     * 
     * @param 
     * @return 
     * @throws 
     * @author <a href=mailto:libin@nryuncang.com>libin</a>
     * @version 1.0.0
     */
    private Map<String, Object> getParameter(ShiroUser curUser, Map<String, String> paramMap) throws Exception{
        
        Map<String, Object> param = new HashMap<String, Object>();

        if (StringUtils.isNotEmpty(paramMap.get("dataRange"))) {
            Map<String, Date> dataMap = DateUtils.getDateRange(paramMap.get("dataRange"));
            Date fromDate = dataMap.get("fromDate");
            Date toDate = dataMap.get("toDate");
            param.put("fromDate", fromDate);
            param.put("toDate", toDate);
        }else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (StringUtils.isNotEmpty(paramMap.get("fromDate"))) {
                param.put("fromDate", sdf.parse(paramMap.get("fromDate") + " 00:00:00"));
            }
            if (StringUtils.isNotEmpty(paramMap.get("toDate"))) {
                param.put("toDate", sdf.parse(paramMap.get("toDate") + "  23:59:59"));
            }
        }
        
        if (StringUtils.isBlank(paramMap.get("customerCode"))) {
            String customerCodes = this.customersService.loadCustomerByAuthority(curUser.jobuuid);
            param.put("customerCodes", StringUtils.isBlank(customerCodes) ? "blank" : customerCodes);
        } else {
            param.put("customerCodes", paramMap.get("customerCode"));
        }
        if (StringUtils.isBlank(paramMap.get("warehouseCode"))) {
            param.put("areagroups", StringUtils.isBlank(curUser.areagroups) ? "blank" : curUser.areagroups);
        } else {
            param.put("areagroups", paramMap.get("warehouseCode"));
        }
        if (!StringUtils.isBlank(paramMap.get("batchCode"))) {
            param.put("batchCode", paramMap.get("batchCode"));
        }
        
        //根据任务号查询
        if (StringUtils.isNotBlank(paramMap.get("taskCode")) && StringUtils.isBlank(paramMap.get("batchCode"))) {
            WorkTask task = this.workTaskService.loadTaskByCode(paramMap.get("taskCode"));
            if (task != null) {
                param.put("batchCode", task.getBatchCode());
            }
        }
        //根据订单号查询
        if (StringUtils.isNotBlank(paramMap.get("orderno")) && StringUtils.isBlank(paramMap.get("batchCode"))) {
            WorkOrder order = this.workOrderService.loadByOrdernoOrCustomerorderno(paramMap.get("orderno"));
            if (order != null) {
                param.put("batchCode", order.getBatchCode());
            }
        }
        
        if (!StringUtils.isBlank(paramMap.get("expressCompany"))) {
            param.put("companyCode", paramMap.get("expressCompany"));
        }
        if (!StringUtils.isBlank(paramMap.get("pickType"))) {
            param.put("pickType", paramMap.get("pickType"));
        }
        
        param.put("status", paramMap.get("status"));
        
        return param;
    }
	
	/**
	 * 作业日志明细
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_workMsgDetail/{batchCode}")
	public String workMsgDetail(@PathVariable("batchCode") String batchCode,Model model) {
		try {
			
			//作业批次
			WorkBatch batch=this.workBatchService.loadWorkBatchByCode(batchCode);
			model.addAttribute("batch",batch);
			
			//订单信息
			Map<String, Object> param=new HashMap<String, Object>();
			param.put("batchCode", batch.getBatchCode());
			List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
			model.addAttribute("orderList",orderList);
			
			//作业日志
			List<WorkLog> logList=this.workLogService.loadLogByBatchCode(batchCode);
			model.addAttribute("logList",logList);
			
			//作业任务信息
			List<WorkTask> taskList=this.workTaskService.loadTaskByBatchCode(batchCode);
			model.addAttribute("taskList",taskList);
			
			  
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/msg/workMsgDetail";
	}
	
	
	
}
